﻿using System;

namespace _5LongestPalindrome
{
    /// <summary>
    /// 给定一个字符串 s，找到 s 中最长的回文子串。你可以假设 s 的最大长度为 1000。
    /// </summary>
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("Hello World!");
            string str = "babab";
            System.Console.WriteLine(IsPalindrome(str));
            System.Console.WriteLine(LongestPalindrome(str));
        }

        public static string LongestPalindrome(string s)
        {
            var temp = s.AsSpan();
            int start = 0;
            int end = 1;
            for (int i = 2; i < temp.Length; i++)
            {
                for (int j = i; j < temp.Length; j++)
                {
                    for (int k = 0; k <= j; k++)
                    {
                        if (IsPalindrome(temp.Slice(k, 2 * (j - k))))
                        {
                            if ((2 * (j - k) - k) > (end - start))
                            {
                                start = j - k;
                                end = j + k;
                            }
                        }
                    }
                }
            }
            return temp.Slice(start, end).ToString();
        }

        private static bool IsPalindrome(ReadOnlySpan<char> readOnlySpan)
        {
            for (int i = 0; i < (readOnlySpan.Length / 2); i++)
            {
                if (readOnlySpan[i] != readOnlySpan[readOnlySpan.Length - i - 1])
                    return false;
            }
            return true;
        }

    }
}
